//
//  StoreViewController.m
//  FKGW
//
//  Created by song ce on 2017/2/21.
//  Copyright © 2017年 song ce. All rights reserved.
//

#import "StoreViewController.h"
#import "StoreCell.h"
#import "SDCycleScrollView.h"
#import "StoreV.h"
#import "SignView.h"
#import "UIView+Extend.h"
#import "StoreSetionView.h"
#import "StorePicModel.h"
#import "SelectedEntryView.h"
#import "EaseMessageViewController.h"
#import "YBPopupMenu.h"
#import "OSSHelper.h"
#import "SelectedChatEntryView.h"

#define KpageCount   @"6"    //每页数据量

@interface StoreViewController ()<UITableViewDelegate,UITableViewDataSource,YBPopupMenuDelegate>
@property(nonatomic,strong)SelectedEntryView *entryView;//选择员工直播入口视图
@property(nonatomic,strong)UITableView *tableV;
@property(nonatomic,strong)SDCycleScrollView *cycleView;//轮播图视图
@property(nonatomic,strong)NSMutableArray *dataSource;//商品数据源
@property(nonatomic,strong)NSMutableArray *picArr;//轮播图oss
@property(nonatomic,strong)NSMutableArray *pathArr;//轮播图本地路径
@property(nonatomic,strong)NSMutableArray *typeArray;//存储分类
@property(nonatomic,strong)SignView *signV;//店铺头像和签名视图

@property(nonatomic,strong)YBPopupMenu *popupMenu;
@property(nonatomic,strong)UIButton   *sortButton;//分类按钮
@property(nonatomic,strong)UIImageView *sortImageV;
@property(nonatomic,strong)UILabel *clabel;
@property(nonatomic,assign)BOOL isPopMenuShowing;//记录分类下啦视图是否显示
@property(nonatomic,assign)CGFloat pointy;
//请求用到的参数
@property(nonatomic,copy)NSString *productName;//商品类别  刷新数据后设置按钮显示的值
@property(nonatomic,copy)NSString *productTypeId;//商品类别id
@property(nonatomic,copy)NSString *salesSortType;//销量排序方式
@property(nonatomic,copy)NSString *priceSortType;//价格排序方式
//下拉刷新相关
@property(nonatomic,assign)NSInteger arrCount;//用于判断上拉加载更多是否有
@property(nonatomic,assign)int indeex;

@property(nonatomic,strong)SelectedChatEntryView *selectedChatEntryView;
@property(nonatomic,copy)NSString *storeCode;
@property(nonatomic,strong)NSMutableArray *chatOnlineArray;

@end

@implementation StoreViewController

- (instancetype)init{
    self = [super init];
    if(self){
        if(!self.isComfromSearchVC){
            //本地路径。创建文件夹  轮播图图片本地化存储路径
            NSString *path=[NSHomeDirectory() stringByAppendingPathComponent:@"Documents/LunboPhotos"];
            BOOL is= [[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:NO attributes:nil error:nil];
            if(is){
                DLog(@"目录创建成功 ");
            }else{
                DLog(@"目录已存在 ");
            }
        }
    }
    return self;
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    //根视图消失的时候将点击次数归零
    [AppDelegate appDealegate].priceClickCount = 0;
    [AppDelegate appDealegate].xiaoliangClickCount = 0;
    if(self.isPopMenuShowing){
        [self showMenuView:self.sortButton];
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    if(self.isComfromSearchVC){
        self.vcName = @"商品查询列表";
    }else{
        self.picArr = [NSMutableArray array];//轮播图图片数据源
        self.pathArr = [NSMutableArray array];//轮播图本地存储路径数组
        self.chatOnlineArray = [NSMutableArray array];
    }
    self.productTypeId = @"";//分类的初始值
    self.salesSortType = @"0";//销量排序初始值
    self.priceSortType = @"0";//价格排序初始值
    self.dataSource = [NSMutableArray array];//商品数据源
    self.typeArray = [NSMutableArray array];//分类数组
    
    //轮播图
    if(!self.isComfromSearchVC){
       [self cyleVIew];
    }
    [self tableViewAndHeaderView];
  
    if(!ISNOTNEEDMESSAGEBTN&&[AppDelegate appDealegate].modelCount==0){
        self.isNeedMessageItem = YES;
    }
    
    if(self.isComfromSearchVC){//从搜索页面过来的
        [self loadSearchData];
    }else{
        //关注、私信、呼叫直播、观看视频
        StoreV *storeV =[[[NSBundle mainBundle]loadNibNamed:@"StoreV" owner:self options:nil]lastObject];
        storeV.left = 0;
        storeV.top = Main_Screen_Height-storeV.height;
        storeV.width = Main_Screen_Width;
        [self.view addSubview:storeV];
        [self.view bringSubviewToFront:storeV];
        
        //-------点击事件回调处理
        __weak typeof(self) weakSelf = self;
        //1,点击了关注按钮
        storeV.focusBlock = ^(BOOL isAttention) {
            if(isAttention){
                 [weakSelf attentionStore];
            }else{
                [weakSelf deAttentionStore:self.storeId];
            }
        };
        
        //2,点击了私信按钮
        storeV.privateMessageBlock = ^{
            [weakSelf showSelectedChatView];
            [weakSelf loadChatEntryData];
        };
        
        //3,点击了呼叫直播按钮
        storeV.callLiveBlock = ^(NSInteger status){
            [MBProgressHUD showTipMessageInWindow:@"该功能正在开发\r\n敬请期待..."];

            if(status==CallLIiveEnabled){//呼叫直播
                
            }else if(status==entryLivingRoom){//进入直播
                
            }
        };
        //4,点击了观看视频按钮
        storeV.watchLiveBlock = ^{
            [MBProgressHUD showTipMessageInWindow:@"该功能正在开发\r\n敬请期待..."];
        };
        [self loadData];
    }
       //加入购物车通知
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(AddToCart:) name:@"jiarugouwuche" object:nil];
 }
//2.66获取店铺在线员工列表
-(void)loadChatEntryData{
    NSDictionary *paramDic = @{@"storeCode":self.storeCode};
    __weak typeof( self) weakSelf = self;
    [Tools AFNetworkingRequestTypePostWithUrl:GETONLINEASSISTANTS paramters:paramDic afterResultBlock:^(NSDictionary *resultDic) {
        DLog(@"获取店铺在线员工列表--%@",resultDic);
        if([resultDic[@"flag"] isEqualToString:@"true"]){
            NSArray *listArr = resultDic[@"data"];
            if([listArr isKindOfClass:[NSNull class]]){
                return ;
            }
            if(self.chatOnlineArray.count){
                [self.chatOnlineArray removeAllObjects];
            }
            for(NSDictionary *dic in listArr){
                ChatEntryModel *model = [ChatEntryModel modelWithDic:dic ];
                [weakSelf.chatOnlineArray addObject:model];
            }
            weakSelf.selectedChatEntryView.dataArray = weakSelf.chatOnlineArray;
        }
    }];
    
}


- (void)showSelectedChatView{
    UIWindow *window = (UIWindow*)[UIApplication sharedApplication].keyWindow;
    [window addSubview:self.maskV];
    [window addSubview:self.selectedChatEntryView];
    self.maskV.userInteractionEnabled = YES;
    __weak typeof (self) weakSelf = self;
    //关闭入口视图
    _selectedChatEntryView.closeBlock=^{
        [weakSelf.maskV removeFromSuperview];
        [weakSelf.selectedChatEntryView removeFromSuperview];
        weakSelf.selectedChatEntryView=nil;
    };
    //建立会话
    _selectedChatEntryView.creatChatBlock = ^(NSString *userName,NSString *nickName) {
            EaseMessageViewController *chatController = [[EaseMessageViewController alloc] initWithConversationChatter:userName conversationType:EMConversationTypeChat];
    chatController.vcName = nickName;
        [weakSelf.maskV removeFromSuperview];
        [weakSelf.selectedChatEntryView removeFromSuperview];
    [weakSelf.navigationController pushViewController:chatController animated:YES];
    };
}

- (SelectedChatEntryView *)selectedChatEntryView{
    if(_selectedChatEntryView==nil){
        _selectedChatEntryView =[[[NSBundle mainBundle]loadNibNamed:@"SelectedChatEntryView" owner:self options:nil]lastObject];
        _selectedChatEntryView.layer.cornerRadius = 5;
        _selectedChatEntryView.layer.masksToBounds = YES;
        
        _selectedChatEntryView.centerX = Main_Screen_Width/2;
        _selectedChatEntryView.centerY = self.view.centerY;
    }
    return _selectedChatEntryView;
}



-(void)loadSearchData{
     [self loadSearchDataWithIndex:0 withPage:@"1"];
}

//2.9首页根据产品名字进行产品模糊查询接口（进入商品展示列表页面）
-(void)loadSearchDataWithIndex:(int)index withPage:(NSString*)page{
    NSDictionary * paraDic= @{@"looseName":self.looseName,
                              @"productTypeId":self.productTypeId,
                              @"salesSortType":self.salesSortType,
                              @"priceSortType":self.priceSortType,
                              @"page":page,
                              @"size":KpageCount
                              };
    __weak typeof(self)  weakSelf = self;
    [MBProgressHUD showLoadingGif];
    [Tools AFNetworkingRequestTypePostWithUrl:SELECTBYLOOSENAME paramters:paraDic  afterResultBlock:^(NSDictionary *resultDic) {
        DLog(@"商品搜索结果----%@",resultDic);
        if([resultDic[@"flag"] isEqualToString:@"true"]){
            NSDictionary *data = resultDic[@"data"];
            if([data isKindOfClass:[NSNull class]]){
                [MBProgressHUD dismissHUD];
                return ;
            }
            
            //类别
            if(!weakSelf.typeArray.count){
                ProductModel *  model = [[ProductModel alloc]init];
                model.name = @"全部";
                model.id = @"";
                [weakSelf.typeArray addObject:model];
                NSArray *typeArr = data[@"productType"];
                for(NSDictionary *tpic in typeArr){
                    ProductModel *pmodel = [[ProductModel alloc]init];
                    pmodel.name = tpic[@"name"];
                    pmodel.id = tpic[@"id"];
                    [weakSelf.typeArray addObject:pmodel];
                }
            }

            NSArray *messageArr = data[@"productMessage"];
            NSMutableArray *startEndArr = [NSMutableArray array];

            for(NSDictionary *mdic in messageArr){
               StoreModel *model = [[StoreModel alloc]init];
                model.imageName = mdic[@"productPic"];
                if([mdic[@"productName"] isKindOfClass:[NSNull class]]){
                    model.goodsName= @"";
                }else{
                    model.goodsName = mdic[@"productName"];
                }
                if([mdic[@"price"] isKindOfClass:[NSNull class]]){
                    model.price = @"";
                }else{
                    model.price = [NSString stringWithFormat:@"%@",mdic[@"price"]];
                }
                model.id = mdic[@"productId"];
                
                if(messageArr.count&&startEndArr.count>messageArr.count-3){
                    model.isNotNeedBottomLine= YES;
                }
                if(messageArr.count<3){
                    model.isNotNeedBottomLine= YES;
                }
                [startEndArr addObject:model];
            }
            if(index==2){
                if(weakSelf.dataSource.count&&messageArr.count){
                    StoreModel *model1 = weakSelf.dataSource.lastObject;
                    model1.isNotNeedBottomLine = NO;
                    StoreModel *model2 = weakSelf.dataSource[weakSelf.dataSource.count-2];
                    model2.isNotNeedBottomLine = NO;
                }
            }else{
                if(weakSelf.dataSource.count){
                    [weakSelf.dataSource removeAllObjects];
                }
            }
            [weakSelf.dataSource addObjectsFromArray:startEndArr];
            weakSelf.arrCount = startEndArr.count;
            if(!weakSelf.dataSource.count){
                [weakSelf.view addSubview:self.noDataIUmageV];
            }else{
                [self.noDataIUmageV removeFromSuperview];
            }
            [weakSelf.tableV reloadData];
            weakSelf.tableV.hidden = NO;
            if(index==0){
                if(startEndArr.count==[KpageCount integerValue]){
                    [weakSelf loadMoreData];
                }else{
                    weakSelf.tableV.mj_footer = nil;
                    weakSelf.tableV.mj_header = nil;
                }
                [MBProgressHUD dismissHUD];
            }
            if([weakSelf.tableV.mj_header isRefreshing]){
                [weakSelf.tableV.mj_header endRefreshing];
            }
            if([weakSelf.tableV.mj_footer isRefreshing]){
                [weakSelf.tableV.mj_footer endRefreshing];
            }
            if(weakSelf.arrCount<[KpageCount intValue]){
                [weakSelf.tableV.mj_footer setState:MJRefreshStateNoMoreData];
            }

        }else{
            [MBProgressHUD dismissHUD];
            if(resultDic[@"errorString"]){
                [MBProgressHUD showTipMessageInWindow:resultDic[@"errorString"]];
            }
        }
    }];
}

-(void)deAttentionStore:(NSString*)storeId{
    // 2.58 取消关注接口
    NSDictionary *paraDic = @{
                              @"userId":USERID,
                              @"storeId":storeId
                              };
    [Tools AFNetworkingRequestTypePostWithUrl:DELMYATTENTION paramters:paraDic  afterResultBlock:^(NSDictionary *resultDic) {
        if([resultDic[@"flag"] isEqualToString:@"true"]){
            [MBProgressHUD showTipMessageInView:@"取消成功"];
        }else{
            if(resultDic[@"errorString"]){
                [MBProgressHUD showTipMessageInWindow:resultDic[@"errorString"]];
            }
        }
    }];
}
//关注店铺接口
-(void)attentionStore{
    //2.22 收藏店铺接口
    NSDictionary *paraDic = @{
                              @"sid":self.storeId,
                              @"uid":USERID
                              };
    
//    __weak typeof(self)  weakSelf = self;
    [Tools AFNetworkingRequestTypePostWithUrl:COLLECTIONSTORE paramters:paraDic  afterResultBlock:^(NSDictionary *resultDic) {
         DLog(@"收藏店铺接口---%@",resultDic);
        if([resultDic[@"flag"] isEqualToString:@"true"]){
            NSDictionary *dataDic = resultDic[@"data"];
            if([dataDic isKindOfClass:[NSNull class]]){
                return ;
            }
            if([dataDic[@"status"] isEqualToString:@"true"]){
                [MBProgressHUD showTipMessageInWindow:@"关注成功"];
            }else{
                if(dataDic[@"errorString"]){
                    [MBProgressHUD showTipMessageInWindow:dataDic[@"errorString"]];
                }
            }
        }else{
            if(resultDic[@"errorString"]){
                [MBProgressHUD showTipMessageInWindow:resultDic[@"errorString"]];
            }
        }
    }];
}
#pragma mark - 加载更多数据
- (void)loadMoreData{
    __weak typeof(self) weakSelf = self;
    self.indeex = 1;
    //上拉加载更多
    self.tableV.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        if(weakSelf.arrCount<[KpageCount intValue]){
            [weakSelf.tableV.mj_footer setState:MJRefreshStateNoMoreData];
        }else{
            self.indeex ++;
            NSString *page = [NSString stringWithFormat:@"%d",self.indeex];
            //参数2 代表操作的是上拉加载更多
            if(self.isComfromSearchVC){
                [weakSelf loadSearchDataWithIndex:2 withPage:page];
            }else{
                [weakSelf loadDataWithIndex:2 withPage:page];
            }
        }
    }];
    
    //下拉刷新
    self.tableV.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        weakSelf.indeex = 1;
        if(self.isComfromSearchVC){
            [weakSelf loadSearchDataWithIndex:1 withPage:@"1"];

        }else{
             [weakSelf loadDataWithIndex:1 withPage:@"1"];
        }
    }];
}
-(void)loadData{
    [self loadDataWithIndex:0 withPage:@"1"];
}
- (void)loadDataWithIndex:(int)index withPage:(NSString*)page{
//  2.12店铺界面接口
    NSDictionary *paraDic = @{
                              @"storeId":self.storeId,
                              @"productTypeId":self.productTypeId,
                              @"salesSortType":self.salesSortType,
                              @"priceSortType":self.priceSortType,
                              @"page":page,
                              @"size":KpageCount
                              };
    __weak typeof(self)  weakSelf = self;
    if(index==0){
        [MBProgressHUD showLoadingGif];
    }
    [Tools AFNetworkingRequestTypePostWithUrl:STOREHOMEPAGE paramters:paraDic  afterResultBlock:^(NSDictionary *resultDic) {
        DLog(@"店铺界面接口---%@",resultDic);
        if([resultDic[@"flag"] isEqualToString:@"true"]){
            NSDictionary *dataDic = resultDic[@"data"];
            if([dataDic isKindOfClass:[NSNull class]]) {
                [MBProgressHUD dismissHUD];
                return ;
            }
            
            //storeCode
            weakSelf.storeCode = dataDic[@"storeCode"];
            //商品内容
            NSArray *messageArr = dataDic[@"productMessage"];
            NSMutableArray *startEndArr = [NSMutableArray array];
            for(NSDictionary *mdic in messageArr){
                StoreModel *model = [[StoreModel alloc]init];
                model.imageName = mdic[@"pic"];
                model.goodsName = mdic[@"productName"];
                model.price = mdic[@"productPrice"];
                model.id = mdic[@"id"];
                if(messageArr.count&&startEndArr.count>messageArr.count-3){
                    model.isNotNeedBottomLine= YES;
                }
                if(messageArr.count<3){
                    model.isNotNeedBottomLine= YES;
                }
                [startEndArr addObject:model];
            }
            
            if(index==2){
                if(weakSelf.dataSource.count&&messageArr.count){
                    StoreModel *model1 = weakSelf.dataSource.lastObject;
                    model1.isNotNeedBottomLine = NO;
                    StoreModel *model2 = weakSelf.dataSource[weakSelf.dataSource.count-2];
                    model2.isNotNeedBottomLine = NO;
                }
            }else{
                if(weakSelf.dataSource.count){
                    [weakSelf.dataSource removeAllObjects];
                }
            }
            [weakSelf.dataSource addObjectsFromArray:startEndArr];
            weakSelf.arrCount = startEndArr.count;
            [weakSelf.tableV reloadData];
            weakSelf.tableV.hidden = NO;
            if(index==0){
                if(startEndArr.count==[KpageCount integerValue]){
                    [weakSelf loadMoreData];
                }else{
                    weakSelf.tableV.mj_footer = nil;
                    weakSelf.tableV.mj_header = nil;
                }
                [MBProgressHUD dismissHUD];
            }
            if([weakSelf.tableV.mj_header isRefreshing]){
                [weakSelf.tableV.mj_header endRefreshing];
            }
            if([weakSelf.tableV.mj_footer isRefreshing]){
                [weakSelf.tableV.mj_footer endRefreshing];
            }
            if(weakSelf.arrCount<[KpageCount intValue]){
                [weakSelf.tableV.mj_footer setState:MJRefreshStateNoMoreData];
            }

            //类别
            if(!weakSelf.typeArray.count){
                ProductModel *  model = [[ProductModel alloc]init];
                model.name = @"全部";
                model.id = @"";
                [weakSelf.typeArray addObject:model];
                                
                NSArray *typeArr = dataDic[@"productType"];
                for(NSDictionary *tpic in typeArr){
                    ProductModel *pmodel = [[ProductModel alloc]init];
                    pmodel.name = tpic[@"name"];
                    pmodel.id = tpic[@"id"];
                    [weakSelf.typeArray addObject:pmodel];
                }
            }
            //轮播图
            if(!weakSelf.picArr.count){
                NSArray *storePics = dataDic[@"storePics"];
                if(storePics.count){
                    for(NSDictionary *picDic in storePics){
                        StorePicModel *picModel = [[StorePicModel alloc]init];
                        picModel.url = picDic[@"url"];
                        //                    picModel.clickUrl = picDic[@"clickUrl"];
                        picModel.no = picDic[@"'no"];
                        [weakSelf.picArr addObject:picModel];
                    }
                    [weakSelf loadIamge];
                }
            }
            //店铺头像和店铺签名
            dispatch_async(dispatch_get_main_queue(), ^{
                NSString *sign ;
                if([dataDic[@"storeSignature"] isKindOfClass:[NSNull class]]){
                    sign = @"";
                }else{
                    sign =  dataDic[@"storeSignature"];
                }
                self.signV.shopSignLabel.text =sign;
            });

            //回到主线程刷新UI
            [[OSSHelper sharedHelper]OSSDownLoadWithObjectKey:dataDic[@"storeHeader"] xOssProcess:[NSString stringWithFormat:@"image/resize,m_lfit,w_%d,h_%d",50,50] downLoadBlock:^(NSData *data) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    NSString *sign ;
                    if([dataDic[@"storeSignature"] isKindOfClass:[NSNull class]]){
                        sign = @"";
                    }else{
                        sign =  dataDic[@"storeSignature"];
                    }
                    self.signV.shopSignLabel.text =sign;
                    self.signV.shopIconImageView.layer.cornerRadius = 25;
                    self.signV.shopIconImageView.layer.masksToBounds = YES;
                    self.signV.shopIconImageView.image = [UIImage imageWithData:data];
                 });
            }];
        }else{
            [MBProgressHUD dismissHUD];
            if(resultDic[@"errorString"]){
                [MBProgressHUD showTipMessageInWindow:resultDic[@"errorString"]];
            }
        }
    }];
}

//这个方法要在数据请求完成的守候调用
- (void)tableViewAndHeaderView{
    //表视图
    if(self.isComfromSearchVC){
        _tableV = [[UITableView alloc]initWithFrame:CGRectMake(0, kNaviBarHeight, Main_Screen_Width, Main_Screen_Height-kNaviBarHeight) style:UITableViewStylePlain];

    }else{
        _tableV = [[UITableView alloc]initWithFrame:CGRectMake(0, kNaviBarHeight, Main_Screen_Width, Main_Screen_Height-kNaviBarHeight-49) style:UITableViewStylePlain];
    }
    _tableV.showsVerticalScrollIndicator = NO;
    _tableV.backgroundColor = DEF_COLOR242;
    _tableV.delegate = self;
    _tableV.dataSource =self;
    [self.view addSubview:_tableV];
    _tableV.tableFooterView = [[UIView alloc]init];
    _tableV.separatorStyle= UITableViewCellSeparatorStyleNone;
  
    if(self.isComfromSearchVC) return;
    
    //店铺头像和签名
    SignView *signV =[[[NSBundle mainBundle]loadNibNamed:@"SignView" owner:self options:nil]lastObject];
    self.signV = signV;
    signV.center = CGPointMake(Main_Screen_Width/2, self.cycleView.height);
    //头视图
    UIView *headV = [[UIView alloc]initWithFrame:CGRectMake(0, 0, Main_Screen_Width, self.cycleView.height+signV.height/2+5)];
    headV.backgroundColor = [UIColor whiteColor];
    [headV addSubview:self.cycleView];
    [headV addSubview:signV];
    _tableV.tableHeaderView = headV;
    _tableV.hidden = YES;
}


//点击店铺详情页面店铺头像接口
- (IBAction)showStoreMessage:(UIButton *)sender {
    [self loadStoreMessage];
    UIWindow *window = (UIWindow*)[UIApplication sharedApplication].keyWindow;
    [window addSubview:self.maskV];
    [window addSubview:self.entryView];
    //设置遮罩视图可以响应事件
    self.maskV.userInteractionEnabled = YES;
    __weak typeof (self) weakSelf = self;
    //选择直播员工页面的关闭按钮回调处理
    _entryView.closeBlock=^{
        [weakSelf.maskV removeFromSuperview];
        [weakSelf.entryView removeFromSuperview];
    };
}
-(void)loadStoreMessage{
    //2.23店铺详情界面点击店铺头像查看店铺信息接口
    NSDictionary *paraDic = @{
                              @"storeId":self.storeId
                              };
        __weak typeof(self)  weakSelf = self;
    [Tools AFNetworkingRequestTypePostWithUrl:STOREMESSAGE paramters:paraDic  afterResultBlock:^(NSDictionary *resultDic) {
        DLog(@"店店铺头像查看店铺信息接口---%@",resultDic);
        if([resultDic[@"flag"] isEqualToString:@"true"]){
            NSDictionary *dataDic = resultDic[@"data"];
            if([dataDic isKindOfClass:[NSNull class]]) return ;
            SelectedEntryModel *model = [[SelectedEntryModel alloc]init];
            model.storePhoto = dataDic[@"storePhoto"];
            model.storeName = dataDic[@"storeName"];
            model.detailedAddress = dataDic[@"detailedAddress"];
            model.purpose = dataDic[@"purpose"];
            model.phone = dataDic[@"phone"];
            model.liveArray = dataDic[@"live"];
            weakSelf.entryView.model = model;
        }else{
            if(resultDic[@"errorString"]){
                [MBProgressHUD showTipMessageInWindow:resultDic[@"errorString"]];
            }
        }
    }];
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSString *ident=@"acqtell";
    StoreCell *cell=[tableView dequeueReusableCellWithIdentifier:ident];
    if(cell==nil){
        cell=[[[NSBundle mainBundle]loadNibNamed:@"StoreCell" owner:self options:nil]lastObject];
    }
    cell.dataSource = self.dataSource;
    return cell;
}

//自定义头视图
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    StoreSetionView *headView =  [[[NSBundle mainBundle]loadNibNamed:@"StoreSetionView" owner:self options:nil]lastObject];
    headView.typeArray = self.typeArray;
    headView.salesSortType = self.salesSortType;
    headView.productName = self.productName;
    headView.priceSortType = self.priceSortType;
    headView.contentView. backgroundColor = [UIColor whiteColor];
    //1,选择了分类
    __weak typeof(self) weakSelf = self;
    headView.sortBlock = ^(UIButton *sender,UIImageView *imageV,UILabel *clabel){
        weakSelf.sortButton = sender;
        weakSelf.sortImageV = imageV;
        weakSelf.clabel = clabel;
        [weakSelf showMenuView:sender];
    };
    //2,点击了销量排序
    headView.saleCountBlock = ^(NSInteger count){
        weakSelf.salesSortType = [NSString stringWithFormat:@"%ld",count];
        weakSelf.priceSortType = @"0";
        [AppDelegate appDealegate].priceClickCount = 0;
        if(weakSelf.isComfromSearchVC){
            [weakSelf loadSearchData];
        }else{
            [weakSelf loadData];
        }
    };
    //3.点击了价格排序
    headView.priceBlock = ^(NSInteger count){
        weakSelf.priceSortType = [NSString stringWithFormat:@"%ld",count];
        weakSelf.salesSortType = @"0";
        [AppDelegate appDealegate].xiaoliangClickCount = 0;
        if(weakSelf.isComfromSearchVC){
            [weakSelf loadSearchData];
        }else{
            [weakSelf loadData];
        }
    };
    return headView;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 45;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if(self.dataSource.count){
        if(self.dataSource.count%2==0){
            return ((Main_Screen_Width-15*3)/2+55+13)*self.dataSource.count/2+18;
        }else{
            return ((Main_Screen_Width-15*3)/2+55+13)*(self.dataSource.count+1)/2+18;
        }
    }
    return 0;
}
-(void)showMenuView:(UIButton *)sender {
    sender.selected = !sender.selected;
    if(sender.isSelected){
        CGFloat y =self.tableV.tableHeaderView.height+33+60-self.pointy;
        _popupMenu = [YBPopupMenu  showAtPoint:CGPointMake(0, y) titles:self.typeArray icons:nil menuWidth:125 view:self.view delegate:self];
        _popupMenu.isShowSeparator = YES;
        _popupMenu.text_Color = [UIColor blackColor];
        _popupMenu.seperaterColor = [UIColor colorWithRed:234./255 green:234./255 blue:234./255 alpha:1.];
//        [sender setImage:[UIImage imageNamed:@"icon_fenleixiala_nor"] forState:UIControlStateSelected];
        self.sortImageV.image = [UIImage imageNamed:@"icon_fenleixiala_nor"];
        self.isPopMenuShowing = YES;
    }else{
        [_popupMenu dismiss];
//        [sender setImage:[UIImage imageNamed:@"icon_hangyexiala_nor"] forState:UIControlStateNormal];
        self.sortImageV.image = [UIImage imageNamed:@"icon_hangyexiala_nor"];
        self.isPopMenuShowing = NO;
    }
}

#pragma mark - YBPopupMenuDelegate
- (void)ybPopupMenuDidSelectedAtIndex:(NSInteger)index ybPopupMenu:(YBPopupMenu*)ybPopupMenu
{
    ProductModel *model = _typeArray[index];
    [self showMenuView:self.sortButton];
//    [self.sortButton setTitle:model.name forState:UIControlStateNormal];
    self.clabel.text = model.name;
    CGFloat with = [self getContentWith:model.name];
    self.clabel.left = (Main_Screen_Width/3-with-5-4.5)/2;
    self.clabel.width = with;
    self.sortImageV.left = self.clabel.right+3;

    
    DLog(@"点击了 %@ 选项",model.name);
    self.productTypeId =model.id;
    self.productName = model.name;
     if(self.isComfromSearchVC){
         [self loadSearchData];
     }else{
           [self loadData];
     }
}

-(CGFloat)getContentWith:(NSString*)content{
    CGRect frame = [content boundingRectWithSize:CGSizeMake(1000, 22) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:15]} context:nil];
    CGFloat with = CGRectGetWidth(frame);
    return with+2;
}


//当视图滑动的时候 如果选择分类的下拉菜单正在 显示就让它消失
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if(scrollView.contentOffset.y<=self.tableV.tableHeaderView.height){
        self.pointy = scrollView.contentOffset.y;
    }
    if(self.isPopMenuShowing){
        [self showMenuView:self.sortButton];
    }
}

//点击左上角的头像选择入口的视图
- (SelectedEntryView *)entryView{
    if(_entryView==nil){
        _entryView =[[[NSBundle mainBundle]loadNibNamed:@"SelectedEntryView" owner:self options:nil]lastObject];
        _entryView.centerX = Main_Screen_Width/2;
        _entryView.centerY = self.view.centerY;
    }
    return _entryView;
}

#pragma mark ---加入购物车接口
-(void)AddToCart:(NSNotification*)noti{
    //2.28用户添加商品到购物车
    NSString *productId = noti.object;
    NSDictionary *paraDic = @{
                              @"productId":productId,
                              @"uid":USERID
                              };
    [Tools AFNetworkingRequestTypePostWithUrl:ADDCART paramters:paraDic  afterResultBlock:^(NSDictionary *resultDic) {
        if([resultDic[@"flag"] isEqualToString:@"true"]){
            NSDictionary *dataDic = resultDic[@"data"];
            if([dataDic isKindOfClass:[NSNull class]]) return ;
            if([dataDic[@"status"] isEqualToString:@"true"]){
                [MBProgressHUD showTipMessageInWindow:@"添加成功"];
            }else{
                if(dataDic[@"errorString"]){
                    [MBProgressHUD showTipMessageInWindow:dataDic[@"errorString"]];
                }
            }
        }else{
            if(resultDic[@"errorString"]){
                [MBProgressHUD showTipMessageInWindow:resultDic[@"errorString"]];
            }
        }
    }];
}

#pragma mark --- 轮播图
- (void)cyleVIew{
    CGFloat cycleScrollViewScale = 1.875;
    CGFloat topViewHeight = Main_Screen_Width/cycleScrollViewScale;
    //轮播图
    self.cycleView = [[SDCycleScrollView alloc] initWithFrame:CGRectMake(0, 0, Main_Screen_Width, topViewHeight)];
    self.cycleView.currentPageDotImage = [UIImage imageNamed:@"lunbodian_nor"];
    self.cycleView.pageDotImage = [UIImage imageNamed:@"lunbodian_sel"];
    self.cycleView.autoScrollTimeInterval = 4.0;
    [self.view addSubview:self.cycleView];
}

-(void)loadIamge{
    __weak typeof(self) weakSelf = self;
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        for(int i = 0;i<self.picArr.count;i++){
            StorePicModel *model = self.picArr[i];
            [[OSSHelper sharedHelper] OSSDownLoadWithObjectKey:model.url  xOssProcess:[NSString stringWithFormat:@"image/resize,m_fill,w_%d,h_%d",(int)(Main_Screen_Width),(int)(Main_Screen_Width*.53)] downLoadBlock:^(NSData *data) {
                //保存到本地
                [weakSelf saveTolocal:data index:i];
            }];
        }
    });
}
-(void)saveTolocal:(NSData*)imageData index:(int)index{
    NSString *imageName ;
    UIImage *image= [UIImage imageWithData:imageData];
    if(UIImagePNGRepresentation(image)){//返回为png图像
        imageName = [NSString stringWithFormat:@"%@.png",[self getTimeNow]];
    }else{ //返回为JPEG图像
        imageName = [NSString stringWithFormat:@"%@.jpg",[self getTimeNow]];
    }
    //本地路径
    NSString *path=[NSHomeDirectory() stringByAppendingPathComponent:@"Documents/LunboPhotos"];
    //创建文件
    path = [path stringByAppendingString:[NSString stringWithFormat:@"/%@",imageName]];
    BOOL isSuccess= [[NSFileManager defaultManager] createFileAtPath:path contents:imageData attributes:nil];
    if(!isSuccess){
        NSLog(@"失败");
    }
    DLog(@"path---%@",path);
    if(isSuccess){
        //回到主线城刷新UI
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.pathArr addObject:path];
            if(self.pathArr.count==self.picArr.count){
                self.cycleView.localizationImageNamesGroup = self.pathArr;
            }
        });
    }
}
- (NSString *)getTimeNow
{
    NSString* date;
    NSDateFormatter * formatter = [[NSDateFormatter alloc ] init];
    [formatter setDateFormat:@"YYYYMMddhhmmssSSS"];
    date = [formatter stringFromDate:[NSDate date]];
    //取出个随机数
    int last = arc4random() % 10000;
    NSString *timeNow = [[NSString alloc] initWithFormat:@"%@-%d", date,last];
    DLog(@"当前时间%@", timeNow);
    return timeNow;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
